#include "BitmapFont.h"
#include "../TinyXML/tinyxml.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"

//Init and Terminate
void BitmapFont::Initialize(std::string file)
{
	SGD::GraphicsManager* graphics = SGD::GraphicsManager::GetInstance();
	TiXmlDocument doc;
	doc.LoadFile(file.c_str());
	TiXmlElement* root = doc.RootElement();
	TiXmlElement* xFile = root->FirstChildElement();
	const char* imageFile = xFile->FirstChildElement()->Attribute("f");
	image = graphics->LoadTexture(imageFile);
	TiXmlElement*chars = xFile->NextSiblingElement();
	int i;
	chars->Attribute("count", &i);
	TiXmlElement* ch = chars->FirstChildElement();
	for (int j = 0; j < i; j++)
	{
		int id, x, y, width, height, xO, yO, xA;
		ch->Attribute("id", &id);
		ch->Attribute("x", &x);
		ch->Attribute("y", &y);
		ch->Attribute("width", &width);
		ch->Attribute("height", &height);
		ch->Attribute("xoffset", &xO);
		ch->Attribute("yoffset", &yO);
		ch->Attribute("xadvance", &xA);
		Character c(x, y, width, height, xO, yO, xA);
		charArray[id] = c;
		ch = ch->NextSiblingElement();
	}
}

void BitmapFont::Terminate()
{
	SGD::GraphicsManager::GetInstance()->UnloadTexture(image);
}

//Draw
void BitmapFont::Draw(const char* output, int x, int y,
	float scale, SGD::Color color) const
{
	SGD::GraphicsManager* graphics = SGD::GraphicsManager::GetInstance();

	int cursor = x;
	int advance = 0;

	for (unsigned int i = 0; output[i]; i++)
	{
		char ch = output[i];
		if (ch == ' ')
		{
			cursor += 10;
		}
		else if (ch == '\n')
		{
			y += 30;
			cursor = x;
		}
		else
		{
			float posX = (float)(charArray[ch].x);
			float posY = (float)(charArray[ch].y);
			float posX2 = (float)(charArray[ch].x + charArray[ch].width);
			float posY2 = (float)(charArray[ch].y + charArray[ch].height);
			SGD::Rectangle rect = { posX, posY, posX2, posY2 };
			graphics->DrawTextureSection(image, { (float)cursor, float(y + charArray[ch].yOffset) }, rect, 0.0f, {},
				color, { scale, scale });
			cursor += (int)(charArray[ch].width * scale);
			advance = charArray[ch].xAdvance;
		}
	}
}